import { useState, useRef, useEffect } from 'react';
import { Button, Layout, Input, List, Typography, Spin, Avatar, Modal } from 'antd';
import { SendOutlined, UserOutlined, RobotOutlined, DeleteOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';
import './App.css';
import styled from 'styled-components';

const { Header, Content, Footer } = Layout;
const { Title, Paragraph } = Typography;
const { TextArea } = Input;

const StyledList = styled(List)`
  .ant-list-item {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    padding: 12px 0;
    border: none;
    animation: fadeIn 0.3s ease;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
`;

const MessageBubble = styled.div`
  position: relative;
  background: ${props => props.isUser ? '#1890ff' : '#f5f5f5'};
  color: ${props => props.isUser ? '#fff' : 'rgba(0, 0, 0, 0.88)'};
  padding: 12px 16px;
  border-radius: 12px;
  max-width: 80%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
`;

function App() {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [copied, setCopied] = useState(false);
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    // 自动聚焦输入框
    inputRef.current?.focus();
  }, []);

  const handleSend = async () => {
    if (!inputValue.trim()) return;

    const userMessage = { role: 'user', content: inputValue };
    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setLoading(true);

    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => {
        controller.abort('请求超时');
      }, 60000);

      const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer sk-pgyvlubqhbmlkwtlcxbryfwjboanqijwvgmwmsjppzzqzofp`,//换成自己的API值 
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          model: 'deepseek-ai/DeepSeek-V3',//模型
          messages: [
            { role: 'system', content: '你是一个有帮助的AI助手。' },
            { role: 'user', content: inputValue }
          ],
          stream: false,
          temperature: 0.7,
          max_tokens: 2000
        }),
        // body: JSON.stringify({
        //   model: 'deepseek-ai/DeepSeek-V3',
        //   messages: [
        //     { role: 'system', content: '你是一个有帮助的AI助手。' },
        //     ...messages.map(msg => ({ role: msg.role, content: msg.content })),
        //     { role: 'user', content: inputValue }
        //   ],
        //   // 其他参数保持不变
        //   stream: false,
        //   temperature: 0.7,
        //   max_tokens: 2000
        // }),
        signal: controller.signal
      }).finally(() => {
        clearTimeout(timeoutId);
      });

      // 处理ai助手回复的数据
      if (!response.ok) {
        const responseText = await response.text();
        console.error('错误响应内容:', responseText);

        let errorMessage;
        try {
          const errorData = JSON.parse(responseText);
          errorMessage = errorData.message || errorData.error || '未知错误';
        } catch {
          errorMessage = responseText || response.statusText;
        }
        throw new Error(`请求失败 (${response.status}): ${errorMessage}`);
      }

      const responseText = await response.text();
      console.log('原始响应:', responseText);

      let data;
      try {
        data = JSON.parse(responseText);
      } catch (e) {
        console.error('JSON解析错误:', e);
        throw new Error('响应格式错误');
      }

      const assistantMessage = {
        role: 'assistant',
        content: data.choices?.[0]?.message?.content || '抱歉，我无法生成回复。'
      };

      setMessages(prev => [...prev, assistantMessage]);

    } catch (error) {
      console.error('错误详情:', {
        message: error.message,
        name: error.name,
        stack: error.stack
      });

      const errorMessage = error.name === 'AbortError'
        ? '请求超时，请稍后重试'
        : `错误: ${error.message}\n类型: ${error.name}\n状态码: ${error.status || '未知'}`;

      setMessages(prev => [...prev, {
        role: 'assistant',
        content: errorMessage
      }]);
    } finally {
      setLoading(false);
    }
  };

  const copyMessage = async (content) => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const clearMessages = () => {
    Modal.confirm({
      title: '确认清空对话',
      content: '是否确认清空所有对话记录？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => setMessages([])
    });
  };

  return (
    <Layout className="layout">
      <Header className="header">
        <div className="header-content">
          <Title level={3} style={{ color: 'white', margin: 0 }}>
            医疗 AI 助手
          </Title>
          {messages.length > 0 && (
            <Button
              type="text"
              icon={<DeleteOutlined />}
              onClick={clearMessages}
              style={{ color: 'white' }}
            >
              清空对话
            </Button>
          )}
        </div>
      </Header>
      <Content className="content">
        <div className="chat-container">
          {messages.length === 0 ? (
            <div className="welcome-screen">
              <RobotOutlined className="welcome-icon" />
              <Title level={2}>欢迎使用 DeepSeek AI 助手</Title>
              <Paragraph>
                您可以问我任何问题，我会尽力帮助您。
              </Paragraph>
              <div className="feature-list">
                <div className="feature-item">
                  <SendOutlined />
                  <span>快速响应</span>
                </div>
                <div className="feature-item">
                  <CopyOutlined />
                  <span>一键复制</span>
                </div>
                <div className="feature-item">
                  <DeleteOutlined />
                  <span>清空对话</span>
                </div>
              </div>
            </div>
          ) : (
            <StyledList
              className="message-list"
              itemLayout="horizontal"
              dataSource={messages}
              renderItem={message => (
                <List.Item
                  style={{
                    display: 'flex',
                    alignItems: 'flex-start',
                    justifyContent: 'flex-start',
                    padding: '12px 0',
                    border: 'none'
                  }}
                >
                  <div className="message-content">
                  
                    <Avatar
                      icon={message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                      className={`avatar ${message.role}`}
                    />
                    <div className="message-bubble-wrapper">
                      <div className="message-bubble">
                        {message.role === 'user' ? (
                          <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                            <span className={/^\d+$/.test(message.content.trim()) ? 'number-display' : ''}>
                              {message.content}
                            </span>
                          </Paragraph>
                        ) : (
                          <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                            {message.content}
                          </Paragraph>
                        )}
                      </div>
                      <div className="message-actions">
                        <Button
                          type="text"
                          size="small"
                          icon={copied ? <CheckOutlined /> : <CopyOutlined />}
                          onClick={() => copyMessage(message.content)}
                          className="action-button"
                        >
                          {copied ? '已复制' : '复制'}
                        </Button>
                      </div>
                    </div>
                  </div>
                </List.Item>
              )}
            />
          )}
          <div ref={messagesEndRef} />
          <div className="input-area">
            <div className="input-container">
              <TextArea
                ref={inputRef}
                value={inputValue}
                onChange={e => setInputValue(e.target.value)}
                placeholder="请输入您的问题..."
                autoSize={{ minRows: 1, maxRows: 6 }}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault();
                    handleSend();
                  }
                }}
                disabled={loading}
                className={loading ? 'input-disabled' : ''}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSend}
                loading={loading}
                className="send-button"
                disabled={!inputValue.trim()}
              />
            </div>
            <div className="input-hint">
              按 Enter 发送，Shift + Enter 换行
            </div>
          </div>
        </div>
      </Content>
      {/* <Footer className="footer">
        DeepSeek AI Assistant ©{new Date().getFullYear()}
      </Footer> */}
    </Layout>
  );
}

export default App; 